package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.entity.Order;
import com.mall.entity.OrderItem;
import com.mall.mapper.OrderMapper;
import com.mall.service.*;
import com.mall.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ShouPeng
 * @since 2023-04-17
 */
@Service
public class OrderServiceImpl implements IOrderService {
    final
    OrderMapper orderMapper;

    final
    IGoodsService goodsService;
    final
    IOrderItemService orderItemService;

    final
    IShoppingCartService shoppingCartService;

    final
    IUserCouponService couponService;

    public OrderServiceImpl(OrderMapper orderMapper, IOrderItemService orderItemService, IShoppingCartService shoppingCartService, IUserCouponService couponService, IGoodsService goodsService) {
        this.orderMapper = orderMapper;

        this.orderItemService = orderItemService;
        this.shoppingCartService = shoppingCartService;
        this.couponService = couponService;
        this.goodsService = goodsService;
    }

    /**
     * 查询订单
     * @param page 页
     * @return list
     */
    @Override
    public IPage<Order> queryOrder(Page<Order> page,String userId) {
        return orderMapper.selectPage(page,new QueryWrapper<Order>().eq("user_id",userId).orderByDesc("order_create_time"));
    }

    /**
     * 用户查询订单
     *
     * @param userId
     * @param orderId
     * @return list
     */
    @Override
    public Order queryOrderById(String userId, String orderId) {
        return orderMapper.selectOne(new QueryWrapper<Order>()
                .eq("user_id",userId)
                .eq("order_id",orderId).orderByDesc("order_create_time"));
    }


    /**
     * 删除订单
     * @param ids ids
     * @return success count
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrder(List<String> ids) {
        for (String id : ids) {
            orderMapper.deleteById(id);
            orderItemService.deleteOrderItemByOrderId(Integer.valueOf(id));
        }
    }

    /**
     * 删除订单
     *
     * @param ids    ids
     * @param userId
     * @return success count
     */
    @Override
    public void deleteOrder(List<String> ids, String userId) {
        for (String id : ids) {
            orderMapper.delete(new QueryWrapper<Order>()
                    .eq("user_id",userId)
                    .eq("order_id",id)
            );
            orderItemService.deleteOrderItemByOrderId(Integer.valueOf(id));
        }
    }

    /**
     * 修改订单
     *
     * @param order entity
     * @return bool
     */
    @Override
    public Boolean updateOrder(Order order) {
        return orderMapper.updateById(order) > 0;
    }

    /**
     * 添加订单
     * @param order entity
     * @return bool
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addOrder(Order order, List<OrderItem> items) throws Exception {
        order.setOrderCreateTime(DateUtils.currentDatetime());
        if (orderMapper.insert(order) > 0) {
            int successCount = 0;
            for (OrderItem item : items) {
                item.setOrderId(String.valueOf(order.getOrderId()));
                successCount += orderItemService.addOrderItem(item) ? 1 : 0;
            }
            if (successCount != items.size()){
                throw new Exception("添加订单失败！");
            }else {
                List<String> ids = items.stream()
                        .map(OrderItem::getShoppingCartId)
                        .collect(Collectors.toList());
                successCount = shoppingCartService.deleteShoppingCart(ids);
                if (successCount != items.size()){
                    throw new Exception("添加订单失败！");
                }

                //使用优惠券
                if (ObjectUtils.isNotEmpty(order.getCouponId())){
                    if (!couponService.useCoupon(order.getCouponId(),order.getUserId())){
                        throw new Exception("添加订单失败！");
                    }
                }
                for (OrderItem item : items) {
                    if (!goodsService.minusGoodsStock(item.getQuantity(), item.getGoodsId())) {
                        throw new Exception("添加订单失败！");
                    }
                }

                return true;
            }
        }else {
            throw new Exception("添加订单失败！");
        }
    }

    /**
     * 用户取消订单
     *
     * @param orderId 订单id
     * @param userId  用户id
     * @return bool
     */
    @Override
    public Boolean setOrderStatus(String orderId, String userId,Integer status,Integer payType) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<Order>()
                .eq("user_id", userId)
                .eq("order_id", orderId)
                .set("status", status);
        if (status == 2){
            updateWrapper
                    .set("is_pay",true)
                    .set("pay_time", DateUtils.currentDatetime())
                    .set("pay_type",payType);
        }
        return orderMapper.update(null, updateWrapper) > 0;
    }

    /**
     * 根据订单号查询订单
     * @param orderNo
     * @return
     */
    @Override
    public Order selectByOrderNo(String orderNo) {
        return orderMapper.selectOne(new QueryWrapper<Order>().eq("order_no",orderNo));
    }
}
